#include "include/relay.h"
#include <zephyr/logging/log.h>

#define RELAY_ON  GPIO_OUTPUT_HIGH
#define RELAY_OFF  GPIO_OUTPUT_LOW
LOG_MODULE_REGISTER(relay);

extern const struct gpio_dt_spec *relay_motor, *relay_stepmotor, *relay_servo;
extern const struct device *uart_motor;

int Relay_init()
{   
    if (!device_is_ready(relay_motor -> port) || !device_is_ready(relay_stepmotor -> port)|| !device_is_ready(relay_servo -> port )) {
        /* Not ready, do not use */
        LOG_ERR("delay device is not ready!");
        return -ENODEV;
	}
    else{
        gpio_pin_configure_dt(relay_motor, RELAY_ON);
        gpio_pin_configure_dt(relay_stepmotor, RELAY_ON);
        gpio_pin_configure_dt(relay_servo, RELAY_ON);
        return 0;
    }
}

int Relay_close(uint8_t num)
{
    if (!device_is_ready(relay_motor -> port) || !device_is_ready(relay_stepmotor -> port)|| !device_is_ready(relay_servo -> port ) ) {
        /* Not ready, do not use */
        LOG_ERR("delay device is not ready!");
        return -ENODEV;
	}
    else{
	    switch(num)
	    {
		    case MOTOR_RELAY:gpio_pin_configure_dt(relay_motor, RELAY_ON);
            break;
		    case STEPMOTOR_RELAY:gpio_pin_configure_dt(relay_stepmotor, RELAY_ON);
            break;
	        case SERVO_RELAY:gpio_pin_configure_dt(relay_servo, RELAY_ON);
	        break;
            case ALL:
                gpio_pin_configure_dt(relay_motor, RELAY_ON);
                gpio_pin_configure_dt(relay_stepmotor, RELAY_ON);
                gpio_pin_configure_dt(relay_servo, RELAY_ON);
                Motor_Ctr_API(uart_motor,Motor_Stop());

            break;
	    }
        return 0;
    }
}
int Relay_open(uint8_t num)
{
	if (!device_is_ready(relay_motor -> port) || !device_is_ready(relay_stepmotor -> port) || !device_is_ready(relay_servo -> port )) {
        /* Not ready, do not use */
        LOG_ERR("delay device is not ready!");
        return -ENODEV;
	}
    else{
	    switch(num)
	    {
		    case MOTOR_RELAY:gpio_pin_configure_dt(relay_motor, RELAY_OFF);
            break;
		    case STEPMOTOR_RELAY:gpio_pin_configure_dt(relay_stepmotor, RELAY_OFF);
            break;
	        case SERVO_RELAY:gpio_pin_configure_dt(relay_servo, RELAY_OFF);
	        break;
            case ALL:
                gpio_pin_configure_dt(relay_motor, RELAY_OFF);
                gpio_pin_configure_dt(relay_stepmotor, RELAY_OFF);
                gpio_pin_configure_dt(relay_servo, RELAY_OFF);
                Motor_Ctr_API(uart_motor,Motor_Stop());
                LOG_ERR("delay device is success!");
            break;
	    }
        return 0;
    }
}
